﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ExamineKeystrokes
{
    class ExamineKeystrokes:Window
    {
        StackPanel stack;
        ScrollViewer scroll;
        string strHeader = "Event     Key          Sys-Key     Text     " + "Ctrl-Text Sys-Text  Ime  KeyStates      " +
            "IsDown IsUp    IsToggled IsRepeat ";
        string strFormatKey = "{0,-10}{1,-20}{2,-10}  {3,-10}{4,-15}{5,-8}{6,-7}{7,-10}{8,-10}";
        string strFormatText = "{0,-10}                     {1,-10}{2,-10}{3,-10}";

        public ExamineKeystrokes()
        {
            this.Title = "Examine Keystrokes";
            this.FontFamily = new System.Windows.Media.FontFamily("Courier New");

            Grid grid = new Grid();
            this.Content = grid;

            RowDefinition rowdef = new RowDefinition();
            rowdef.Height = GridLength.Auto;
            grid.RowDefinitions.Add(rowdef);
            grid.RowDefinitions.Add(new RowDefinition());

            TextBlock textHeader = new TextBlock();
            textHeader.FontWeight = FontWeights.Bold;
            textHeader.Text = strHeader;
            grid.Children.Add(textHeader);

            this.scroll = new ScrollViewer();
            grid.Children.Add(this.scroll);
            Grid.SetRow(this.scroll, 1);

            this.stack = new StackPanel();
            this.scroll.Content = this.stack;
        }

        void DisplayInfo(string str)
        {
            TextBlock text = new TextBlock();
            text.Text = str;
            this.stack.Children.Add(text);
            this.scroll.ScrollToBottom();
        }

        void DisplayKeyInfo(KeyEventArgs args)
        {
            string str = string.Format(this.strFormatKey, args.RoutedEvent.Name, args.Key, args.SystemKey, args.ImeProcessedKey, args.KeyStates,
                args.IsDown, args.IsUp, args.IsToggled, args.IsRepeat);
            this.DisplayInfo(str);
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            this.DisplayKeyInfo(e);
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            base.OnKeyUp(e);
            this.DisplayKeyInfo(e);
        }

        protected override void OnTextInput(TextCompositionEventArgs e)
        {
            base.OnTextInput(e);
            string str = string.Format(this.strFormatText, e.RoutedEvent.Name, e.Text, e.ControlText, e.SystemText);
            this.DisplayInfo(str);
        }

        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new ExamineKeystrokes());
        }
    }
}
